package com.ruoyi.cqjd.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.cqjd.common.BaseContext;
import com.ruoyi.cqjd.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.cqjd.domain.CqjdUser;
import com.ruoyi.cqjd.service.ICqjdUserService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 用户Controller
 *
 * @author ruoyi
 * @date 2022-06-19
 */
@RestController
@RequestMapping("/cqjd/cqjd_user")
@Slf4j
public class CqjdUserController extends BaseController {
    @Autowired
    private ICqjdUserService cqjdUserService;


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 给手机号发送验证码
     *
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody CqjdUser user, HttpSession session) {
        String phone = user.getPhone();
        if (StringUtils.isNotBlank(phone)) {
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
//            发送验证码，这里没有使用真的短信服务，毕竟要钱，所以只是控制台输出一下
            log.info("验证码为：{}", code);
//            把验证码保存到session中
//            session.setAttribute(phone, code);
//            将验证码保存到redis中，同时设置过期时间为5分钟
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
//            return R.success("验证码发送成功");
            return R.ok("验证码发送成功");
        }
        return R.fail("验证码发送失败");

    }


    @PostMapping("/logout")
    public R  logout(HttpSession session) {
        //销毁session中用户登录的信息
        session.invalidate();
        //重定向到首页
//        resp.sendRedirect(req.getContextPath());
        return R.ok();
    }

    @PostMapping("/login")
    public R<CqjdUser> login(@RequestBody Map<String, String> map, HttpSession session) {
//        获取手机号
        String phone = map.get("phone");
//        获取验证码
        String code = map.get("code");
//        获取session中的验证码
//        Object codeInSession = session.getAttribute(phone);
//        从redis中获取验证码
        Object codeInSession = redisTemplate.opsForValue().get(phone);
//        比对验证码
        if (codeInSession != null && codeInSession.equals(code)) {
//        如果验证码相同，看手机号是否是新的，新的就保存

            CqjdUser user = cqjdUserService.getUserByPhone(phone);
            if (user == null) {
                user = new CqjdUser();
                user.setPhone(phone);
                cqjdUserService.insertCqjdUser(user);
//                cqjdUserService.save(user);

                user = cqjdUserService.getUserByPhone(phone);
            }
//            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
//            queryWrapper.eq(User::getPhone, phone);
//            User user = userService.getOne(queryWrapper);
//            if (user == null) {
//                user = new User();
//                user.setPhone(phone);
//                userService.save(user);
//
//            }

            session.setAttribute("user",user.getId());

//            BaseContext.setCurrentId(user.getId());
//            如果登录成功，就删除redis中的验证码
            redisTemplate.delete(phone);
            return R.ok(user);
        }
//        如果验证码不相同，返回登录失败
        return R.fail("登录失败");
    }

    /**
     * 查询用户列表
     */
//    @PreAuthorize("@ss.hasPermi('cqjd:cqjd_user:list')")
    @GetMapping("/list")
    public TableDataInfo list(CqjdUser cqjdUser) {
        startPage();
        List<CqjdUser> list = cqjdUserService.selectCqjdUserList(cqjdUser);
        return getDataTable(list);
    }

    /**
     * 导出用户列表
     */
//    @PreAuthorize("@ss.hasPermi('cqjd:cqjd_user:export')")
    @Log(title = "用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CqjdUser cqjdUser) {
        List<CqjdUser> list = cqjdUserService.selectCqjdUserList(cqjdUser);
        ExcelUtil<CqjdUser> util = new ExcelUtil<CqjdUser>(CqjdUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    /**
     * 获取用户详细信息
     */
//    @PreAuthorize("@ss.hasPermi('cqjd:cqjd_user:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(cqjdUserService.selectCqjdUserById(id));
    }

    /**
     * 新增用户
     */
//    @PreAuthorize("@ss.hasPermi('cqjd:cqjd_user:add')")
    @Log(title = "用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CqjdUser cqjdUser) {
        return toAjax(cqjdUserService.insertCqjdUser(cqjdUser));
    }

    /**
     * 修改用户
     */
//    @PreAuthorize("@ss.hasPermi('cqjd:cqjd_user:edit')")
    @Log(title = "用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CqjdUser cqjdUser) {
        return toAjax(cqjdUserService.updateCqjdUser(cqjdUser));
    }

    /**
     * 删除用户
     */
//    @PreAuthorize("@ss.hasPermi('cqjd:cqjd_user:remove')")
    @Log(title = "用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(cqjdUserService.deleteCqjdUserByIds(ids));
    }
}
